<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 15:13
 */
namespace App\Services;

use App\Repositories\DistributGroupRepository;
use App\Repositories\DistributProfitRepository;
use App\Repositories\UserLevelPassageBankRepository;
use App\Repositories\UserLevelPassageRepository;
use App\Repositories\UserLevelProfitRepository;
use App\Repositories\UserProfitRepository;
use App\Repositories\UserRepository;

class UserProfitService extends CommonService
{
    protected $userProfitRepository;
    protected $userRepository;
    protected $userLevelProfitRepository;
    protected $userLevelPassageRepository;
    protected $userLevelPassageBankRepository;
    protected $distributGroupRepository;
    protected $distributProfitRepository;
    protected $messageService;

    public function __construct(UserProfitRepository $userProfitRepository,
                                UserRepository $userRepository,
                                UserLevelProfitRepository $userLevelProfitRepository,
                                UserLevelPassageRepository $userLevelPassageRepository,
                                UserLevelPassageBankRepository $userLevelPassageBankRepository,
                                DistributGroupRepository $distributGroupRepository,
                                DistributProfitRepository $distributProfitRepository,
                                MessageService $messageService)
    {
        $this->userProfitRepository = $userProfitRepository;
        $this->userRepository = $userRepository;
        $this->userLevelProfitRepository = $userLevelProfitRepository;
        $this->userLevelPassageRepository = $userLevelPassageRepository;
        $this->userLevelPassageBankRepository = $userLevelPassageBankRepository;
        $this->distributGroupRepository = $distributGroupRepository;
        $this->distributProfitRepository = $distributProfitRepository;
        $this->messageService = $messageService;
    }

    /**
     * 账户收益
     * @param $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function accountProfit($user)
    {
        //账户余额
        $data['account_balance'] = $user['account_balance'];
        //总收益
        $data['profit_all'] = $this->userProfitRepository->profitAll($user['user_id']);
        //收益类型： 1好友升级 2好友还款 3好友收款 4交易返现 5办理贷款 6办信用卡
        $upgradeProfitAll = $this->userProfitRepository->profitFromTypeSum($user['user_id'], 1);
        $upgradeProfitToday = $this->userProfitRepository->profitFromTypeToday($user['user_id'], 1);
        $upgradeProfitCount = $this->userProfitRepository->profitFromTypeCount($user['user_id'], 1);
        $repaymentProfitAll = $this->userProfitRepository->profitFromTypeSum($user['user_id'], 2);
        $repaymentProfitToday = $this->userProfitRepository->profitFromTypeToday($user['user_id'], 2);
        $repaymentProfitCount = $this->userProfitRepository->profitFromTypeCount($user['user_id'], 2);
        $cashProfitAll = $this->userProfitRepository->profitFromTypeSum($user['user_id'], 3);
        $cashProfitToday = $this->userProfitRepository->profitFromTypeToday($user['user_id'], 3);
        $cashProfitCount = $this->userProfitRepository->profitFromTypeCount($user['user_id'], 3);
        $tradeProfitAll = $this->userProfitRepository->profitFromTypeSum($user['user_id'], 4);
        $tradeProfitToday = $this->userProfitRepository->profitFromTypeToday($user['user_id'], 4);
        $tradeProfitCount = $this->userProfitRepository->profitFromTypeCount($user['user_id'], 4);
        $loanProfitAll = $this->userProfitRepository->profitFromTypeSum($user['user_id'], 5);
        $loanProfitToday = $this->userProfitRepository->profitFromTypeToday($user['user_id'], 5);
        $loanProfitCount = $this->userProfitRepository->profitFromTypeCount($user['user_id'], 5);
        $creditCardProfitAll = $this->userProfitRepository->profitFromTypeSum($user['user_id'], 6);
        $creditCardProfitToday = $this->userProfitRepository->profitFromTypeToday($user['user_id'], 6);
        $creditCardProfitCount = $this->userProfitRepository->profitFromTypeCount($user['user_id'], 6);
        $data['list'] = [
            'upgrade' => [
                'profit_all' => $upgradeProfitAll,
                'profit_today' => $upgradeProfitToday,
                'profit_count' => $upgradeProfitCount,
            ],
            'repayment' => [
                'profit_all' => $repaymentProfitAll,
                'profit_today' => $repaymentProfitToday,
                'profit_count' => $repaymentProfitCount,
            ],
            'cash' => [
                'profit_all' => $cashProfitAll,
                'profit_today' => $cashProfitToday,
                'profit_count' => $cashProfitCount,
            ],
            'trade' => [
                'profit_all' => $tradeProfitAll,
                'profit_today' => $tradeProfitToday,
                'profit_count' => $tradeProfitCount,
            ],
            'loan' => [
                'profit_all' => $loanProfitAll,
                'profit_today' => $loanProfitToday,
                'profit_count' => $loanProfitCount,
            ],
            'credit_card' => [
                'profit_all' => $creditCardProfitAll,
                'profit_today' => $creditCardProfitToday,
                'profit_count' => $creditCardProfitCount,
            ],
        ];
        //是否有设置支付密码
        $userInfo = $this->userRepository->byId($user['user_id']);
        $data['is_has_paypwd'] = empty($userInfo->paypwd) ? 0 : 1;
        return $this->responseJson(0, $data);
    }

    /**
     * 收益明细
     * @param $user
     * @param $profitType
     * @return \Illuminate\Http\JsonResponse
     */
    public function profitDetail($user, $profitType)
    {
        $monthProfit  = $this->userProfitRepository->groupByMonthProfit($user['user_id'], $profitType);
        $data = [];
        foreach ($monthProfit as $key=>$value) {
            $data[$key]['record'] = $value;
            $detail = $this->userProfitRepository->byMonthAll($user['user_id'], $profitType, $value['create_month']);
            foreach ($detail as $kk=>$vv) {
                $fromUser = $this->userRepository->byId($vv['from_user_id']);
                $detail[$kk] = $vv;
                $detail[$kk]['head_pic'] = getOssImageUrl($fromUser->head_pic);
                $detail[$kk]['mobile'] = hiddenMobile($fromUser->mobile);
                $detail[$kk]['realname'] = hiddenRealName($fromUser->realname);
            }
            $data[$key]['detail'] = $detail;
        }
        return $this->responseJson(0, $data);
    }

    /**
     * @param $getProfitUserLevel
     * @param $money
     * @param $rate
     * @param $profitType '收益类型： 1好友升级 2好友还款 3好友收款 4交易返现 5办理贷款 6办信用卡'
     * @param $passageId
     * @param $bankCode
     * @param $userOwnMobile
     * @param $fromProfitSn
     * @param $profit
     * @param $fromUserId
     * @param $toUserId
     * @param $messageTemplateId
     * @param int $directOrIndirect
     * @return float|int
     */
    public function userProfit($getProfitUserLevel, $money, $rate, $profitType,
                               $passageId, $bankCode, $beProfitUserMobile, $fromProfitSn,
                               $profit, $fromUserId, $toUserId, $messageTemplateId, $directOrIndirect = 0)
    {
        //1服务商 2代言人才有分润
        $directRelations = $this->userLevelProfitRepository->byToProfitPercent($getProfitUserLevel, $profitType);
        $profitPercent = 0;
        //直接
        if ($directOrIndirect == 0) {
            $profitPercent = $directRelations->direct_profit_percent;
        }
        //间接
        if ($directOrIndirect == 1) {
            $profitPercent = $directRelations->indirect_profit_percent;
        }
        $clearingRate = 0;
        if ($passageId > 0) {
            $levelPassage = $this->userLevelPassageRepository->first($passageId, $getProfitUserLevel);
            if ($levelPassage->type == 0) {
                $clearingRate = $levelPassage->clearing_rate;//结算费率
            }
            if ($levelPassage->type == 1) {
                $userLevelPassageBank = $this->userLevelPassageBankRepository->passageToBank($passageId, $bankCode, $getProfitUserLevel);
                $clearingRate = $userLevelPassageBank->clearing_rate;//结算费率
            }
        }
        $directOrIndirectProfit = $this->profitLevel($money, $rate, $clearingRate, $profitPercent);
        if ($directOrIndirectProfit == 0) {
            return $directOrIndirectProfit;
        }
        //对应收益人的账户余额
        $userProfit = $this->userRepository->byId($toUserId);
        //归属分销商id
        $distributId = $userProfit->belong_to_distribut_id;
        if ($distributId > 0) {
            $distributGroup = $this->distributGroupRepository->findGroupMember($distributId, $toUserId);
            $distributProfit = roundNo($directOrIndirectProfit * $distributGroup->profit_percent);
            if ($distributProfit > 0) {
                $distributProfitBill = [
                    'profit_no' => makeOrderNo(),
                    'from_profit_sn' => $fromProfitSn,
                    'revenue_money' => $directOrIndirectProfit,
                    'profit_money' => $distributProfit,
                    'profit_percent' => $distributGroup->profit_percent,
                    'from_group_id' => $distributGroup->id,
                    'to_distribut_id' => $distributGroup->distribut_id,
                    'profit_type' => $profitType,
                    'create_time' => time(),
                    'create_date' => date('Y-m-d'),
                    'create_month' => date('Y-m'),
                ];
                $this->distributProfitRepository->insertGetId($distributProfitBill);
                //分销商账户余额
                $distributUser = $this->userRepository->byId($distributGroup->distribut_user_id);
                $distributAccountBalance = $distributUser->account_balance + $distributProfit;
                $distributUser->update(['account_balance' => $distributAccountBalance]);
            }
            $profitMoney = $directOrIndirectProfit - $distributProfit;
        } else {
            $profitMoney = $directOrIndirectProfit;
        }
        $data = [
            'profit_no' => makeOrderNo(),
            'from_profit_sn' => $fromProfitSn,
            'revenue_money' => $profit,
            'profit_money' => $profitMoney,
            'from_user_id' => $fromUserId,
            'to_user_id' => $toUserId,
            'profit_type' => $profitType,
            'create_time' => time(),
            'create_month' => date('Y-m'),
        ];
        $detailId = $this->userProfitRepository->insertGetId($data);
        $accountBalance = $userProfit->account_balance + $profitMoney;
        $invitedCode = $userProfit->invited_code;
        $userProfit->update(['account_balance' => $accountBalance]);
        //发送好友收益消息提醒
        $this->messageService->messageTemplate($messageTemplateId, $invitedCode, '', '',
            $profitMoney, '', $beProfitUserMobile, $detailId, '', '');
        return $directOrIndirectProfit;
    }
}